from typing import Any, Optional
from pydantic import BaseModel
from fastapi.responses import JSONResponse


class ApiResponse(BaseModel):
    """统一API响应模型"""
    code: int
    msg: str
    data: Optional[Any] = None


class ResponseCode:
    """响应码常量"""
    SUCCESS = 0  # 成功
    UNAUTHORIZED = 401  # 未授权
    FORBIDDEN = 403  # 禁止访问
    NOT_FOUND = 404  # 未找到
    BAD_REQUEST = 400  # 请求错误
    INTERNAL_ERROR = 500  # 内部服务器错误


class ResponseMsg:
    """响应消息常量"""
    SUCCESS = "操作成功"
    UNAUTHORIZED = "非法用户，请登录后再试"
    FORBIDDEN = "没有权限访问"
    NOT_FOUND = "未找到相关资源"
    BAD_REQUEST = "请求参数错误"
    INTERNAL_ERROR = "内部服务器错误"


def success_response(data: Any = None, msg: str = ResponseMsg.SUCCESS) -> JSONResponse:
    """返回成功响应"""
    response = ApiResponse(code=ResponseCode.SUCCESS, msg=msg, data=data)
    return JSONResponse(content=response.model_dump())


def error_response(code: int, msg: str, data: Any = None) -> JSONResponse:
    """返回错误响应"""
    response = ApiResponse(code=code, msg=msg, data=data)
    return JSONResponse(content=response.model_dump())


def unauthorized_response(msg: str = ResponseMsg.UNAUTHORIZED) -> JSONResponse:
    """返回未授权响应"""
    return error_response(ResponseCode.UNAUTHORIZED, msg)


def forbidden_response(msg: str = ResponseMsg.FORBIDDEN) -> JSONResponse:
    """返回禁止访问响应"""
    return error_response(ResponseCode.FORBIDDEN, msg)


def not_found_response(msg: str = ResponseMsg.NOT_FOUND) -> JSONResponse:
    """返回未找到响应"""
    return error_response(ResponseCode.NOT_FOUND, msg)


def bad_request_response(msg: str = ResponseMsg.BAD_REQUEST) -> JSONResponse:
    """返回请求错误响应"""
    return error_response(ResponseCode.BAD_REQUEST, msg)


def internal_error_response(msg: str = ResponseMsg.INTERNAL_ERROR) -> JSONResponse:
    """返回内部服务器错误响应"""
    return error_response(ResponseCode.INTERNAL_ERROR, msg)


def create_response(code: int = 200, msg: str = "操作成功", data: Any = None) -> JSONResponse:
    """
    创建统一的响应格式
    
    Args:
        code: 响应状态码
        msg: 响应消息
        data: 响应数据
    
    Returns:
        JSONResponse: 统一格式的JSON响应
    """
    response = ApiResponse(code=code, msg=msg, data=data)
    return JSONResponse(content=response.model_dump()) 